import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入一级路由组件
// 导入登录
import Login from '@/views/login'
// 后台系统布局组件
import Layout from '@/views/layout'

// 导入二级路由组件
// 默认首页
import Home from '@/views/home'
// 文章管理
import Articles from '@/views/articles'
// 发表文章
import AddArticle from '@/views/addArticle'
// 编辑文章
import EditArticle from '@/views/editArticle'
// 素材管理
import Image from '@/views/image'
// 评论管理
import Comment from '@/views/comment'
// 粉丝管理
import Fans from '@/views/fans'
// 个人设置
import Setting from '@/views/setting'
// 404页面
import NotFound from '@/views/notFound'

// 获取token
import { getToken } from '@/utils/store'

// 处理新版router异常
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(() => { })
}

Vue.use(VueRouter)

const routes = [
  // 后台系统基础骨架
  {
    path: '/',
    component: Layout,
    // 重定向
    // redirect: '/home',
    // redirect: { name: 'home' },
    children: [
      // 默认首页
      {
        path: '/',
        name: 'Home',
        component: Home
      },
      // 其他功能页面
      {
        // 文章管理
        path: '/articles',
        name: 'Articles',
        component: Articles
      },
      // 发表文章
      {
        path: '/addArticle',
        name: 'AddArticle',
        component: AddArticle
      },
      {
        // 编辑文章
        path: '/editArticle',
        name: 'EditArticle',
        component: EditArticle
      },
      // 素材管理
      {
        path: '/image',
        name: 'Image',
        component: Image
      },
      // 评论管理
      {
        path: '/comment',
        name: 'Comment',
        component: Comment
      },
      // 粉丝管理
      {
        path: '/fans',
        name: 'Fans',
        component: Fans
      },
      // 个人设置
      {
        path: '/setting',
        name: 'Setting',
        component: Setting
      }
    ]
  },
  {
    // 登录
    path: '/login',
    name: 'Login',
    component: Login
  },
  // 404页面
  {
    path: '*',
    name: 'NotFound',
    component: NotFound
  }
]

// 路由实例
const router = new VueRouter({
  routes
})

// 拦截页面访问
router.beforeEach((to, from, next) => {
  const token = getToken()?.token
  if (!token && to.path !== '/login') {
    // 调回登录页
    next('/login')
  } else if (token && to.path === '/login') {
    return next('/')
  }
  next()
})
export default router
